package com.dongdongshop.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    //shiro的过滤器链
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        factoryBean.setSecurityManager(securityManager);
        //定义过滤器
        Map<String,String> map = new LinkedHashMap<>();//表示对于这种类型的map存取有序
        map.put("/shoplogin","anon");//anon 不需要登录直接放过 过滤器
        map.put("/index","anon");
        map.put("/getSellerLogin","anon");
        map.put("/js/**","anon");
        //map.put("/**","authc");//authc:必须登录才能访问
        //factoryBean.setUnauthorizedUrl("/unauthorized");//设置权限跳转的路径
        //默认跳转login.jsp  需要修改跳转路径
        factoryBean.setLoginUrl("/tologin");
        //将map放进过滤器工厂类中
        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }
//实例化安全管理器
    @Bean//实例化对象 将这个对象引入上一个对象 用@Autowired依赖注入
    public DefaultWebSecurityManager securityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置realm 要查询数据库 所以需要自己创建类  并将类在下方实例化
        securityManager.setRealm(loginRealm);
        return securityManager;
    }

    //实例化自己定义的realm类
    @Bean  //注入到DefaultWebSecurityManager
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm realm = new LoginRealm();
        realm.setCredentialsMatcher(hashedCredentialsMatcher);
        return realm;
    }

    @Bean//开启后 set给realm
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        //加密的工具类
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //1.加密算法的名字
        credentialsMatcher.setHashAlgorithmName("MD5");
        //2.加密的次数
        credentialsMatcher.setHashIterations(3);
        //3.设置编码(编码要统一)
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }
}
